package organisms;

import java.util.ArrayList;

import processing.core.PApplet;
import field.AngleField;
import field.FieldInterpreter;
import geom.Geom;
import geom.PolarVector;
import geom.Segment;
import geom.Vector;
import cluster.*;
import color.*;

public class ColorTracer extends Tracer{
	Cluster<Color> ancestry;
	Duster<Color> color;
	float refColorDist = new Color(new Rgb(0, 0, 0)).distanceTo(new Color(new Rgb(255, 255, 255)));

	
	public ColorTracer(PApplet pa, Cluster<Color> ancestry, AngleField field, Vector pos, Vector speed) {
		super(pa, field, pos, speed);
		this.ancestry = ancestry;
		ArrayList<Duster<Color>> colors = ancestry.root.getLeafs();
		color = colors.get((int) Math.floor(Math.random()*colors.size()));
	}

	public void drawTrace(){
		if(!draw) return;
		pa.noFill();
		pa.strokeWeight(2);
		
		color.getCentroid().stroke(pa, 255);
		if(prevPos != null)pa.line(prevPos.x, prevPos.y, pos.x, pos.y);
	}
	
	protected class Interpreter extends FieldInterpreter{
		float maxLength;
		public Interpreter(Organism parent, AngleField field) {
			super(parent, field);
			maxLength = field.getBinSize().absLength();
		}

		

		@Override
		public Vector process(Segment seg, ArrayList<Segment> segments) {
			if(!seg.getParent().getParent().equals(this)){
				
				float dist = Geom.getDistanceFromPointToLineXY(seg.startPos(), seg.endPos(), pos) - 5f;
				//float scaled = sigE(1 / dist, 128f);
				Vector head = seg.relative();
				if(head.absLength() > Math.sqrt(maxLength)){
					head.scaleLengthTo((float)Math.sqrt(maxLength));
				}
				float distance = ((ColorTracer)seg.getParent().getParent()).color.getDistanceTo(
						((ColorTracer)parent).color);
				//head.a = head.a % (float)Math.PI;
				return head.mult(0.1f / (1 + (float)Math.pow(Math.E, dist/16f))/* + 1f / (distance/refColorDist + 0.1f)*/);	
			}
			return null;
			
		}
		@Override
		public Vector postProcess(Vector fieldValue, ArrayList<Segment> segments) {
			fieldValue =  fieldValue.div((segments.size() + 1) / 16f);
			PApplet.println("fval 1: " + fieldValue);
			PolarVector p = fieldValue.getPolar();
			p.a = p.a % 2f;
			p.e = p.e % 2f;
			
			fieldValue = p.getCartesian();
			PApplet.println("fval 2: " + fieldValue);
			
			return fieldValue;
		}
	}
	
	public void draw(){
		color.getCentroid().stroke(pa);
		super.draw();
	}

}
